<template>
  <view class="">
    <view class="xian_"> </view>
    <movable-area class="drag-sort" :style="{ height: boxHeight }" id="drag">
      <movable-view
        v-for="(item, index) in currentList"
        :key="index"
        :x="item.x"
        v-if="item.isShow === 1"
        :y="item.y"
        :direction="direction"
        disabled
        damping="40"
        :animation="item.animation"
        class="drag-sort-item"
        :style="styleObject"
        :class="{ active: active == index, 'vh-1px-t': item.index > 0 }"
      >
        <image
          @touchstart="touchstart"
          @touchmove.stop="touchmove"
          @touchend="touchend"
          :data-index="index"
          src="../../imges/tuodong.png"
          mode="aspectFill"
          class="tuodong"
        ></image>
        <view class="item">
          <text>{{ item.label }}</text>
        </view>
        <view class="shuxian"> </view>
        <image
          src="../../imges/cha.png"
          mode="aspectFill"
          class="shanchu"
          @click="close(index, item.id)"
        ></image>
      </movable-view>
    </movable-area>
  </view>
</template>

<script>
import request from "../../utils/request.js";
export default {
  name: "drag-sort",
  mixins: [],
  components: {},
  data() {
    return {
      styleObject: {
        color: "#888888",
        fontSize: "28px",
      },
      direction: "all",
      windowWidth: 100, //屏幕宽度
      height: 50, // 高度
      currentList: [],
      active: -1, // 当前激活的item
      index: 0, // 当前激活的item的原index
      topY: 0, // 距离顶部的距离
      topX: 0, // 距离左侧偏移位置
      deviationX: 0,
      deviationY: 0, // 偏移量
    };
  },
  computed: {
    boxHeight() {
      return Math.ceil((Number(this.list.length) + 1) / 2) * this.height + "px";
    },
  },
  props: {
    list: {
      type: Array,
      default: () => {
        return [];
      },
    },
    boxStyle: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    list: {
      handler() {
        // debugger
        this.onUpdateCurrentList();
      },
      deep: true,
    },
  },
  created() {
    const res = uni.getSystemInfoSync();
    this.windowWidth = res.windowWidth;
    this.onUpdateCurrentList();
  },
  mounted() {},
  updated() {},
  filters: {},
  methods: {
    onUpdateCurrentList(list = this.list) {
      let arr = [];
      for (const key in list) {
        let height = Math.ceil((Number(key) + 1) / 2) - 1;
        let x = 0;
        if (key <= 1) {
          x =
            key * this.windowWidth * 0.5 + this.windowWidth * 0.02 ||
            this.windowWidth * 0.02;
        } else {
          if ((Number(key) + 1) % 2 == 0) {
            x =
              1 * this.windowWidth * 0.5 + this.windowWidth * 0.02 ||
              this.windowWidth * 0.02;
          } else {
            x =
              (((Number(key) + 1) % 2) - 1) * this.windowWidth * 0.5 +
                this.windowWidth * 0.02 || this.windowWidth * 0.02;
          }
        }
        arr.push({
          //循环数组赋值
          ...list[key],
          isShow: 1,
          index: Number(key),
          SortNumber: Number(key),
          y: height * this.height,
          x,
          animation: true,
        });
      }
      this.currentList = arr;
      // console.log(this.currentList, '初始数据') //初始数据
    },
    // 根据排序进行重新计算位置
    moveUpdateCurrentList(index) {
      for (const i in this.currentList) {
        let key;
        if (
          this.currentList[i].SortNumber ||
          this.currentList[i].SortNumber === 0
        ) {
          key = this.currentList[i].SortNumber;
        } else {
          key = Number(i);
        }
        // console.log(key,'移动的key')
        let temobj = { ...this.currentList[i] };
        // debugger
        this.currentList[i].y =
          (Math.ceil((Number(key) + 1) / 2) - 1) * this.height;
        if (index == key) {
          continue;
        } else {
          if (key <= 1) {
            this.currentList[i].x =
              key * this.windowWidth * 0.5 + this.windowWidth * 0.02 ||
              this.windowWidth * 0.02;
          } else {
            if ((Number(key) + 1) % 2 == 0) {
              this.currentList[i].x =
                1 * this.windowWidth * 0.5 + this.windowWidth * 0.02 ||
                this.windowWidth * 0.02;
            } else {
              this.currentList[i].x =
                (((Number(key) + 1) % 2) - 1) * this.windowWidth * 0.5 +
                  this.windowWidth * 0.02 || this.windowWidth * 0.02;
            }
          }
        }
      }
    },
    touchstart(e) {
      // 计算 x y 轴点击位置
      var query = uni.createSelectorQuery().in(this);
      query.select("#drag").boundingClientRect();
      query.exec((res) => {
        this.topY = res[0].top;
        this.topX = res[0].left;
        let touchY = e.mp.touches[0].clientY - res[0].top;
        let touchX = e.mp.touches[0].clientX - res[0].left;
        this.deviationY = touchY % this.height;
        this.deviationX = touchX % (this.windowWidth * 0.2);
        this.active = Number(e.currentTarget.dataset.index);
        this.index = Number(e.currentTarget.dataset.index);
      });
    },
    touchmove(e) {
      if (this.active < 0) return;
      let temY = e.mp.touches[0].clientY - this.topY;
      let temX = e.mp.touches[0].clientX - this.topX;
      let touchY = temY - 15;
      let touchX = temX - this.windowWidth * 0.1;
      this.currentList[this.active].y = touchY;
      this.currentList[this.active].x = touchX;
      this.currentList[this.active].animation = false;
      this.currentList.every((res, index) => {
        let absX = Math.abs(touchX - res.x);
        let absY = Math.abs(touchY - res.y);
        // 设置元素定点距离多少进行重排
        if (
          0 < absX &&
          absX <= 10 &&
          absY > 0 &&
          absY <= 10 &&
          this.active != index
        ) {
          // debugger
          let temNumber = this.currentList[index].SortNumber;
          this.currentList.every((_res, _index) => {
            // 判断从大像小移还是从小向大移
            if (
              this.currentList[this.active].SortNumber <
              this.currentList[index].SortNumber
            ) {
              // 移动元素比目标元素所在位置小，之间元素排序--
              if (
                this.currentList[_index].SortNumber >
                  this.currentList[this.active].SortNumber &&
                this.currentList[_index].SortNumber <=
                  this.currentList[index].SortNumber
              ) {
                _res.SortNumber--;
              }
            } else {
              // 反之++
              if (
                this.currentList[_index].SortNumber <
                  this.currentList[this.active].SortNumber &&
                this.currentList[_index].SortNumber >=
                  this.currentList[index].SortNumber
              ) {
                _res.SortNumber++;
              }
            }
            return true;
          }, this);
          this.currentList[this.active].SortNumber = temNumber;
          this.moveUpdateCurrentList(temNumber); //调用重新排序
          return false;
        } else {
          return true;
        }
      }, this);
    },
    touchend(e) {
      if (this.currentList[this.active]) {
        this.currentList[this.active].animation = true;
      }
      this.$emit("change", this.currentList); //把新数组返回给父组件
      this.moveUpdateCurrentList(-1); //调用重新排序
      this.active = -1;
    },
    // 关闭按钮
    close(index, id) {
      //调用删除接口
      //    	console.log(index,'删除索引')
      // console.log(id,'删除id')
      uni.showModal({
        title: "提示",
        content: "您确定要删除这个标签吗？",
        cancelColor: "#007aff",
        cancelText: "再想想",
        confirmColor: "#000",
        success: (re) => {
          if (re.confirm) {
            if (id) {
              //编辑标签
              let token = uni.getStorageSync("token");
              // console.log(token, 'token')
              if (!token) {
                uni.showToast({
                  title: "请授权登录再操作！",
                  duration: 2000,
                  icon: "none",
                });
                setTimeout(() => {
                  uni.navigateTo({
                    url: "/pages/index/index",
                  });
                }, 2000);
              } else {
                request({
                  url: "app/orgCircle/removeFriendsLabel",
                  method: "POST",
                  header: {
                    "Content-Type": "application/json",
                    "api-client": "72e0fee8172411ea995200163e05ff66",
                    "api-version": "1.3.3",
                    "Source-Type": 7,
                    token: token,
                  },
                  data: {
                    id: id,
                  },
                }).then((res) => {
                  // console.log(res, '删除')
                  if (res.data.code == 200) {
                    this.currentList.forEach((item, i) => {
                      if (
                        this.currentList[i].SortNumber >
                        this.currentList[index].SortNumber
                      ) {
                        item.SortNumber--;
                      }
                    });
                    this.moveUpdateCurrentList(-1); //调用重新排序
                    this.currentList[index].isShow = 0;
                    uni.showToast({
                      title: "删除成功！",
                      duration: 2000,
                      icon: "none",
                    });
                  } else {
                    uni.showToast({
                      title: res.data.msg,
                      duration: 2000,
                      icon: "none",
                    });
                  }
                });
              }
            } else {
              //新增标签
              this.currentList.forEach((item, i) => {
                if (
                  this.currentList[i].SortNumber >
                  this.currentList[index].SortNumber
                ) {
                  item.SortNumber--;
                }
              });
              this.moveUpdateCurrentList(-1); //调用重新排序
              this.currentList[index].isShow = 0;
              uni.showToast({
                title: "删除成功！",
                duration: 2000,
                icon: "none",
              });
              // console.log(this.currentList)
              let arrL = this.currentList.filter((v) => {
                return v.isShow == 1;
              });
              uni.setStorageSync("labelList", arrL);
            }
          }
        },
      });
    },
  },
};
</script>

<style lang='less' scoped>
@import "~./1px.less";

.xian_ {
  width: 100%;
  height: 2rpx;
  background-color: #eee;
  margin-bottom: 35rpx;
}

.shuxian {
  width: 2rpx;
  height: 18rpx;
  background-color: #ccc;
  position: relative;
  left: -30rpx;
}

.tuodong {
  display: inline-block;
  width: 35rpx;
  height: 45rpx;
  position: relative;
  z-index: 66666666;
  right: -25rpx;
}

.shanchu {
  width: 20rpx;
  height: 20rpx;
  position: relative;
  left: -20rpx;
}

.drag-sort {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.drag-sort-item {
  position: absolute !important;
  display: flex;
  height: 62rpx;
  align-items: center;
  width: 46%;
  text-align: center;
  border: 1rpx solid rgba(136, 136, 136, 1);
  border-radius: 31rpx;
  color: #fff;
  box-sizing: border-box;

  .item {
    position: relative;
    flex: 1;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    text {
      display: inline-block;
      width: 220rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 1;
      overflow: hidden;
    }
  }

  .close {
    position: absolute;
    right: -10upx;
    top: -10upx;
    width: 30upx;
    z-index: 99;
    height: 30upx;
    opacity: 0.8;
  }

  .close image {
    width: 100%;
    height: 100%;
  }

  .touch-tight {
    width: 24px;
    display: flex;
    justify-content: center;
  }
}

.touch {
  height: 100%;
  width: 50px;
}

.active {
  box-shadow: 0 0 40rpx #dddddd;
  z-index: 99;
}
</style>
